<template>
	<cl-dialog
		title="管理分公司"
		width="700px"
		:visible.sync="visible"
		:before-close="beforeClose"
		@close="close"
		:props="{
			top: '5vh',
			closeOnClickModal: false
		}"
	>
		<el-form ref="form" :model="form" :rules="rules" label-position="top" :disabled="saving">
			<el-form-item label="管理分公司" prop="is_assign" required>
				<el-radio-group v-model="form.is_assign" @change="isAssignChange">
					<el-radio :label="0">全部</el-radio>
					<el-radio :label="1">指定</el-radio>
				</el-radio-group>
			</el-form-item>
			<el-form-item
				label="指定分公司"
				prop="manage_subsidiary_ids"
				v-if="form.is_assign == 1"
			>
				<el-checkbox-group v-model="form.manage_subsidiary_ids">
					<el-row>
						<el-col :span="8" v-for="(item, index) in companyList" :key="index">
							<el-checkbox :label="item.company_id" name="manage_subsidiary_ids">
								{{ item.company_name }}
							</el-checkbox>
						</el-col>
					</el-row>
				</el-checkbox-group>
			</el-form-item>
		</el-form>
		<template #footer>
			<el-button @click="close">关闭</el-button>
			<el-button type="primary" @click="submit" :loading="saving">确定</el-button>
		</template>
	</cl-dialog>
</template>

<script>
export default {
	name: "manage-branch",
	data() {
		return {
			visible: false,
			saving: false,
			form: {
				user_id: "",
				is_assign: 0, // 是否指定
				manage_subsidiary_ids: []
			},
			rules: {
				manage_subsidiary_ids: [{ required: true, message: "请选择分公司" }]
			},
			companyList: []
		};
	},
	methods: {
		open(data = {}) {
			this.visible = true;
			this.form.user_id = data.user_id;
			let is_assign = data.manage_subsidiary_id == "*" ? 0 : 1;
			this.form.is_assign = is_assign;
			this.form.manage_subsidiary_ids =
				is_assign == 0
					? []
					: (data.manage_subsidiary_id || "")
							.split(",")
							.filter(Boolean)
							.map(Number);
			this.getCompany(data);
		},
		beforeClose(done) {
			if (this.saving) return;
			done();
		},
		close() {
			if (this.saving) return;
			this.visible = false;
			this.reset();
		},
		reset() {
			this.saving = false;
			this.$refs.form.resetFields();
		},
		isAssignChange(v) {
			if (v) {
				this.form.manage_subsidiary_ids = [];
			}
		},
		submit() {
			this.$refs.form.validate(async (valid, errors) => {
				this.showFormErr(errors);
				if (!valid) return;
				try {
					this.saving = true;
					const { is_assign, manage_subsidiary_ids, ...args } = this.form;
					let form = {
						...args,
						subsidiary: is_assign ? manage_subsidiary_ids.join() : "*"
					};
					await this.$service.company.setUserManage(form);
					this.$message.success("操作成功");
					this.$emit("confirm");
					this.saving = false;
					this.close();
				} catch (error) {
					this.saving = false;
				}
			});
		},
		//分公司
		async getCompany(data) {
			this.companyList =
				(await this.$store.dispatch("common/getBizCompany", {
					biz_id: data.biz_id,
					needAll: false
				})) || [];
		}
	}
};
</script>
